package cn.hp.log;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import cn.hp.domain.SysLog;
import cn.hp.service.LogService;

//通知类


public class LogController {
	
	@Autowired
	private HttpServletRequest httpServletRequest;
	@Autowired
	private LogService logService;
	
	
	
	//通知:增强的代码
	
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
		//1.创建日志对象
		SysLog log=new SysLog();
		//2.将日志对象封装
		
		//访问的时间
		log.setVisitTime(new Date());
		
		
		//访问的用户名
		//获取安全框架的上下文对象
		SecurityContext securityContext = SecurityContextHolder.getContext();
		//获取认证信息
		Authentication authentication = securityContext.getAuthentication();
		//获取用户(重要)信息
		User user= (User) authentication.getPrincipal();
		//获取用户名
		String username=user.getUsername();
		log.setUsername(username);
		
		//访问的IP地址
		String ip = httpServletRequest.getRemoteAddr();
		log.setIp(ip);
		
		//访问的方法   全限定名.方法名
		Object target = joinPoint.getTarget();
		String className = target.getClass().getName();
		
		Signature signature = joinPoint.getSignature();
		String methodName = signature.getName();
		log.setMethod(className+"."+methodName);
		System.out.println(log);  
		
		//3.将日志信息存储到数据库
		logService.save(log);
		
		
		
		
		
		//环绕通知之前的部分
		Object proceed = joinPoint.proceed();
		//环绕通知之后的部分
		return proceed;
	}
}
